<?php
/**
 * Created by PhpStorm.
 * User: jason
 * Date: 2018/12/24
 * Time: 0:14
 */

namespace App\Http\Controllers\Admin\Traits;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

trait ProxyHelpers
{
    /**
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function authenticate()
    {
        $client = new Client();

        try {
            $url = request()->root() . '/admin/oauth/token';

            $params = array_merge(config('passport.proxy'), [
                'username' => request('username'),
                'password' => request('password'),
                'provider' => 'admins'
            ]);

            $respond = $client->post($url, ['form_params' => $params]);
        } catch (RequestException $exception) {
            abort(401, $exception->getMessage());
        }

        if ($respond->getStatusCode() !== 401) {
            return json_decode($respond->getBody()->getContents(), true);
        }

       abort(401, '账号或密码错误');
    }

    public function getRefreshToken()
    {
        $client = new Client();

        try {
            $url = request()->root() . 'admin/oauth/token';

            $params = array_merge(config('passport.proxy'), [
                'refresh_token' => request('refresh_token'),
            ]);

            $respond = $client->post($url, ['form_params' => $params]);
        } catch (RequestException $exception) {
            abort(401, '请求失败，服务器错误');
        }

        if ($respond->getStatusCode() !== 401) {
            return json_decode($respond->getBody()->getContents(), true);
        }

        abort(401, 'refresh_token 错误');
    }
}